const express = require('express');
const router = express.Router();
const moment = require('moment');
const User = require('../models/User')
const Card = require('../models/Card');
const Comment = require('../models/Comment');



router.post('/addComment', async (req, res) => {
    try {
        // 从请求体中获取评论相关信息
        const { commenterId, cardId, content } = req.body.params;
        // 首先检查评论者和卡片是否存在
        const commenter = await User.findById(commenterId);
        const card = await Card.findById(cardId);
        if (!commenter || !card) {
            return res.status(404).json({ message: '评论者或卡片不存在' });
        }
        const newComment = new Comment({
            commenter: commenterId,
            content,
            createdAt: moment().format('YYYY-MM-DD HH:mm'),
            like: 0
        });
        // 保存评论到数据库
        const savedComment = await newComment.save();
        // 将评论添加到卡片的评论数组中
        card.comment.push(savedComment._id);
        await card.save();
        // 返回成功的响应
        return res.status(201).json({ message: '评论成功', comment: savedComment });
    } catch (error) {
        // 处理错误情况
        console.error(error);
        return res.status(500).json({ message: '服务器错误' });
    }
})
//获取卡片的接口
router.get('/getComment', async (req, res) => {
    try {
        const id = req.query._id;
        const cardData = await Card.findOne({ _id: id });
        if (cardData) {
            const commentIds = cardData.comment;
            const comments = await Comment.find({ _id: { $in: commentIds } }).populate('commenter');
            const commentData = comments.map(comment => ({
                commentId: comment._id,
                author: {
                    _id: comment.commenter._id,
                    username: comment.commenter.username,
                    avatar: comment.commenter.avatar,
                },
                content: comment.content,
                createdAt: comment.createdAt,
                like: comment.like,
            }));
            console.log(commentData);
            res.status(200).json(commentData);
        } else {
            console.log('没找到卡片');
            res.status(404).json({ message: '卡片未找到' });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
})

module.exports = router;